package com.theme.passport.controller.theme;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.theme.common.base.ConfigConstant;
import com.theme.common.mvc.exception.RRException;
import com.theme.common.mvc.utils.PageUtils;
import com.theme.common.mvc.validator.ValidatorUtils;
import com.theme.common.mvc.validator.group.AddGroup;
import com.theme.common.mvc.view.R;
import com.theme.passport.controller.oss.cloud.OSSFactory;
import com.theme.passport.controller.sys.AbstractController;
import com.theme.passport.entity.SysUserEntity;
import com.theme.passport.entity.theme.ThemeEntity;
import com.theme.passport.form.PasswordForm;
import com.theme.passport.service.SysUserService;
import com.theme.passport.service.theme.ThemeService;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Arrays;
import java.util.List;
import java.util.Map;


/**
 * 设计师用户
 *
 * @author live
 * @email 870459550@qq.com
 * @date 2020-07-10 14:30:04
 */
@RestController
@RequestMapping("theme/designer")
public class DesignerController extends AbstractController {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private ThemeService themeService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("theme:designer:list")
    public R list(@RequestParam Map<String, Object> params){

        PageUtils page = sysUserService.queryPage(params);

        return R.ok().put("page", page);
    }

    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("theme:designer:info")
    public R info(@PathVariable("id") Long id){
        SysUserEntity designer = sysUserService.getById(id);
        QueryWrapper<ThemeEntity> orderWrapper = new QueryWrapper<>();
        orderWrapper.and(wrapper -> wrapper.eq("user_id", id));
        List<ThemeEntity> list = themeService.list(orderWrapper);
        designer.setThemeList(list);
        return R.ok().put("designer", designer);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("theme:designer:save")
    public R save(@RequestBody SysUserEntity themeDealer){
        ValidatorUtils.validateEntity(themeDealer, AddGroup.class);

        themeDealer.setCreateUserId(getUserId());
        sysUserService.saveDesigner(themeDealer);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("theme:designer:update")
    public R update(@RequestBody SysUserEntity themeDealer){
        themeDealer.setPassword(null);
        themeDealer.setSalt(null);
        sysUserService.updateById(themeDealer);
        return R.ok();
    }


    /**
     * 修改登录用户密码
     */
    @PostMapping("/password")
    @RequiresPermissions("theme:designer:update")
    public R password(@RequestBody PasswordForm form){

        SysUserEntity designer = sysUserService.getById(form.getUserId());

        //sha256加密
        String salt = RandomStringUtils.randomAlphanumeric(20);
        designer.setPassword(new Sha256Hash(form.getPassword(), salt).toHex());
        designer.setSalt(salt);

        sysUserService.updateById(designer);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("theme:designer:delete")
    public R delete(@RequestBody Long[] ids){
        sysUserService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }

    /**
     * 上传文件
     */
    @PostMapping("/uploadAvatar")
    public R uploadAvatar(@RequestParam("img") MultipartFile file) throws Exception {
        if (file.isEmpty()) {
            throw new RRException("上传文件不能为空");
        }

        String originalFilename = file.getOriginalFilename();
        String fileExpandName = originalFilename.substring(originalFilename.lastIndexOf(".") + 1, originalFilename.length());
        if (!ConfigConstant.filePattern.matcher(fileExpandName.toUpperCase()).find()) {
            return R.error("文件格式不支持");
        }

        //上传文件
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        String url = OSSFactory.build(null).uploadSuffix(file.getBytes(), suffix);

        return R.ok().put("filePath", url);
    }

}
